package leetcode.code0846;

import java.util.Arrays;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

/**
 * 内存溢出
 */
public class Solution4 implements IDebug {

	public boolean isNStraightHand(int[] hand, int groupSize) {
		if (groupSize == 1)
			return true;
		Arrays.sort(hand);
		int len = hand.length;
		int min = hand[0];
		int max = hand[len - 1];
		int range = max - min + 1;
		if (groupSize - 1 >= range) {
			return false;
		}
		int[] hash = new int[range];
		for (int i = 0; i < len; i++) {
			hash[hand[i] - min]++;
		}
		int[] help = new int[range];
		help[0] += -hash[0];
		help[groupSize - 1] += hash[0];
		int sum = help[0];
		int num = 0;
		for (int i = 1; i < range; i++) {
			int cur = i;// 数字
			int sub = hash[i];// 个数
			if (sum != 0 && num + 1 != cur) {
				return false;
			}
			num = cur;
			int diff = sum + sub;
			if (diff != 0) {
				help[i] += -diff;
				if (i + groupSize - 1 >= range) {
					return false;
				}
				help[i + groupSize - 1] += diff;
			}
			sum += help[i];
		}
		return true;
	}

	@Override
	public void debug1() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[5,1]"), 1));

	}

	public void debug6() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[3,4,5]"), 3));

	}

	public void debug5() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,1,2,2,3,3]"), 4));

	}

	@Override
	public void debug2() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,4,5]"), 4));

	}

	@Override
	public void debug3() {
		HelpDebug.compare(false, this.isNStraightHand(HelpDebug.str2array3(
				"[233722108,386144634,221638886,175028874,408337082,91410299,793763682,972910825,627251147,135020779]"),
				2));

	}

	@Override
	public void debug4() {
		HelpDebug.compare(true, this.isNStraightHand(HelpDebug.str2array3("[1,2,3,6,2,3,4,7,8]"), 3));

	}

	public static void main(String[] args) {
		Solution4 so = new Solution4();
//		so.debug6();
//		so.debug5();
//		so.debug1();
//		so.debug2();
		so.debug3();
//		so.debug4();

	}

}
